const openid = getApp().globalData.openid;

Page({
    data: {
        // 左侧菜单
        buyMemo: [],
        // 右侧全部列表
        buyList: [],
        // 右侧选中列表
        rightContent: [],
        // 当前选中的菜单项
        currentIndex: 0,
        // 切换菜单项时右侧列表滚动位置置顶
        scrollTop: 0,
        // 弹窗显示加入的菜的图片
        imgUrl: "../../icon/eat.png",
        fileId: "",
        // 弹窗显示加入的菜的名字
        name: "香辛料",
        // 重量
        weight: "×1",
        // 计量单位
        unit: "份",
        // 已选几样
        count: 0,
        // 隐藏弹窗
        shadowDisplay: "none",
        addMemoDisplay: "none",
        addCateDisplay: "none",
        addListDisplay: "none",
        imgDisplay: "block",
        // 警告提醒
        warnText: "",
        warnVisibility: "hidden",
        warnAnimation: {},
        decreaseColor: "gray"
    },

    //左侧菜单的点击事件
    updatePage(e) {
        const index = e.currentTarget.dataset.index;
        const list = this.data.buyList[index];
        let rightContent;
        if (list) {
            rightContent = list;
        } else {
            rightContent = null;
        }
        this.setData({
            currentIndex: e.currentTarget.dataset.index,
            rightContent: rightContent,
            scrollTop: 0
        })
    },

    //点击加入备忘录按钮显示弹窗
    showPopWindow(e) {
        this.setData({
            shadowDisplay: "block",
            addMemoDisplay: "block",
            imgUrl: e.currentTarget.dataset.img,
            name: e.currentTarget.dataset.name,
            fileId: e.currentTarget.dataset.fileid
        });
    },

    //点击灰色透明区域取消弹窗
    cancelAdd(e) {
        this.setData({
            shadowDisplay: "none",
            addMemoDisplay: "none",
            addCateDisplay: "none",
            addListDisplay: "none",
            weight: "×1",
            unit: "份",
            decreaseColor: "gray"
        })
    },

    // 选择计量单位
    chooseUnit(e) {
        let unit = e.currentTarget.dataset.unit;
        if (unit == "default") {
            this.setData({
                unit: "份",
                weight: "×1"
            });
        } else if (unit == "Kg") {
            this.setData({
                unit: unit,
                weight: "0.5"
            });
        } else if (unit == "g") {
            this.setData({
                unit: unit,
                weight: "100"
            });
        } else {
            this.setData({
                unit: unit,
                weight: "1"
            });
        }
        this.setData({
            decreaseColor: "gray"
        });
    },

    //点击确定添加按钮 添加到备忘录
    add(e) {
        if (this.data.weight == "") {
            this.showWarning("请先输入需要的重量！");
        } else {
            let data = this.data
            this.setData({
                count: data.count + 1
            })
            let newItem = {
                imgUrl: data.imgUrl,
                name: data.name,
                weight: data.weight,
                unit: data.unit,
                fileId: data.fileId
            };
            let buyChoosed = wx.getStorageSync('buyChoosed');
            if (!buyChoosed) {
                buyChoosed = new Array();
            }
            buyChoosed.push(newItem);
            wx.setStorageSync('buyChoosed', buyChoosed);

            // 显示添加成功动画
            this.setData({
                imgDisplay: "block"
            })
            let animation = wx.createAnimation({
                delay: 0,
                duration: 1000,
                timingFunction: "ease"
            })
            animation.translate(-20, 100).scale(0.01).step();
            this.setData({
                closeAnimation: animation.export()
            });

            // 关闭弹窗
            let that = this;
            setTimeout(function () {
                animation.translate(0).scale(1).step();
                that.setData({
                    closeAnimation: animation.export(),
                    imgDisplay: "none",
                    unit: "份",
                    weight: "×1",
                    decreaseColor: "gray"
                })
                that.cancelAdd();
            }, 1200);
        }
    },

    //从组件获取weight更新
    updateData(e) {
        this.setData({
            weight: e.detail
        })
    },

    //添加自定义菜单项
    addCate(e) {
        this.setData({
            shadowDisplay: "block",
            addCateDisplay: "block"
        })
    },
    onUpdateBuyMemo(e) {
        let temp = this.data.buyMemo;
        if (!temp) {
            temp = [];
        }
        temp.push(e.detail);
        this.setData({
            buyMemo: temp
        });
        wx.setStorageSync('buyMemo', temp);
    },

    //添加自定义菜品
    addList(e) {
        this.setData({
            shadowDisplay: "block",
            addListDisplay: "block"
        })
    },
    onUpdateBuyList(e) {
        let index = this.data.currentIndex;
        let temp = this.data.buyList[index];
        if (!temp) {
            temp = [];
        }
        temp.push(e.detail);
        this.setData({
            ["buyList[" + index + "]"]: temp,
            rightContent: temp
        });
        wx.setStorageSync('buyList', this.data.buyList);
    },

    // 点击中间弹窗的确认添加关闭弹窗
    oncloseHandler(e) {
        let that = this;
        if (e.detail) {
            setTimeout(function () {
                that.cancelAdd();
            }, 1800);
        }
    },

    //添加自定义时没有输入名称显示警告弹窗
    onwarnHandler() {
        this.showWarning("还没有输入名称！");
    },

    // 显示警告弹窗
    showWarning(text) {
        this.setData({
            warnText: text,
            warnVisibility: "visible"
        });
        let animation = wx.createAnimation({
            delay: 0,
            duration: 800,
            timingFunction: "ease"
        });
        animation.opacity(1).step();
        this.setData({
            warnAnimation: animation.export()
        });
        let that = this;
        setTimeout(function () {
            animation.opacity(0).step();
            that.setData({
                warnAnimation: animation.export()
            })
        }, 2300);
        setTimeout(function () {
            that.setData({
                warnVisibility: "hidden"
            })
        }, 3100);
    },

    //长按删除buymemo项
    deleteMemoItem(e) {
        wx.showModal({
            title: "提示",
            content: '确定要删除“' + e.currentTarget.dataset.name + '”吗? 您保存的该项所有数据都将丢失！',
            success: res => {
                if (res.confirm) {
                    let buyMemo = this.data.buyMemo;
                    let buyList = this.data.buyList;
                    //从数组中删去这一项并保存到缓存
                    let deleteMemo = buyMemo.splice(e.currentTarget.dataset.index, 1);
                    let deleteList = buyList.splice(e.currentTarget.dataset.index, 1);
                    this.setData({
                        buyMemo: buyMemo,
                        buyList: buyList
                    });
                    wx.setStorageSync('buyMemo', buyMemo);
                    wx.setStorageSync('buyList', buyList);

                    //删除云储存中该项对应的右侧列表中用户自定义的图片
                    let fileList = []
                    if(deleteList[0]) {
                        for(let i = 0; i < deleteList[0].length; i++) {
                            if(deleteList[0][i].fileId.indexOf("userImages") >= 0) {
                               fileList.push(deleteList[0][i].fileId);
                            }
                        }
                        wx.cloud.deleteFile({
                            fileList: fileList,
                            success: res => {
                                console.log("删除" + deleteMemo[0] + "中用户自定义的全部图片成功");
                            },
                            fail: err => {
                                console.log("删除用户自定义图片失败" + err);
                            }
                        });
                    }

                    //如果删除的是当前正在查看的种类，就显示上一个种类
                    if (this.data.currentIndex == e.currentTarget.dataset.index) {
                        let buyListItem = this.data.buyList[this.data.currentIndex - 1];
                        if (!buyListItem) {
                            buyListItem = {}
                        }
                        this.setData({
                            currentIndex: this.data.currentIndex - 1,
                            rightContent: buyListItem
                        });
                    }
                    wx.showToast({
                        title: '删除成功',
                    });
                }
            }
        })
    },

    //长按删除buyList项
    deleteListItem(e) {
        wx.showModal({
            title: "提示",
            content: '确定要删除“' + e.currentTarget.dataset.name + '”吗?',
            success: res => {
                if (res.confirm) {
                    let buyList = this.data.buyList;
                    //从数组中删去这一项并保存到缓存 
                    let deleteItem = buyList[this.data.currentIndex].splice(e.currentTarget.dataset.index, 1);
                    this.setData({
                        buyList: buyList,
                        rightContent: buyList[this.data.currentIndex]
                    });
                    wx.setStorageSync('buyList', buyList);
                    wx.showToast({
                        title: '删除成功',
                    });

                    //如果删除的是用户自定义数据就删除云储存中对应的图片
                    if(deleteItem[0].fileId.indexOf("userImages") >= 0) {
                        wx.cloud.deleteFile({
                            fileList: [deleteItem[0].fileId],
                            success: res => {
                                console.log("删除云图片成功");
                            },
                            fail: err => {
                                console.log("删除云图片失败" + err);
                            }
                        });
                    } else {
                        console.log("系统默认图片，不进行删除操作");
                    }
                }
            }
        })
    },

    //加载初始数据
    onLoad: function (options) {
        let buyMemoStorage = wx.getStorageSync('buyMemo');
        let buyListStorage = wx.getStorageSync('buyList');
        var that = this;

        //当本地缓存存在时从本地缓存加载数据,不存在时从云端获取个人数据保存在本地缓存
        if (buyMemoStorage) {
            this.setData({
                buyMemo: buyMemoStorage
            });
        } else {
            wx.cloud.database().collection("buyMemo").doc(openid).get({
                //如果云端储存了用户的个人数据就加载个人数据
                success: res => {
                    wx.setStorageSync('buyMemo', res.data.buyMemo);
                    that.setData({
                        buyMemo: res.data.buyMemo
                    });
                },
                //如果没有储存就加载默认初始数据
                fail: err => {
                    that.setData({
                        buyMemo: wx.getStorageSync('defaultBuyMemo')
                    })
                    wx.setStorageSync('buyMemo', wx.getStorageSync('defaultBuyMemo'))
                }
            });

        }

        if (buyListStorage) {
            this.setData({
                buyList: buyListStorage,
                rightContent: buyListStorage[0]
            });
        } else {
            wx.cloud.database().collection("buyList").doc(openid).get({
                //如果云端储存了用户的个人数据就加载个人数据
                success: res => {
                    let buyList = res.data.buyList;
                    for (let i = 0; i < buyList.length; i++) {
                        if (buyList[i]) {
                            for (let j = 0; j < buyList[i].length; j++) { //这里可以先只加载第一项的图片数据来节省流量，
                                wx.cloud.downloadFile({                   //甚至只加载第一页的前几项，后面的通过下拉刷新加载，后面改一下
                                    fileID: buyList[i][j].fileId,
                                    success: res => {
                                        buyList[i][j].imgUrl = res.tempFilePath;
                                        wx.setStorageSync('buyList', buyList);
                                        that.setData({
                                            buyList: buyList,
                                            rightContent: buyList[0]
                                        });
                                    }
                                })
                            }
                        }
                    }
                },
                //如果没有储存就加载默认初始数据
                fail: err => {
                    this.setData({
                        buyList: wx.getStorageSync('defaultBuyList'),
                        rightContent: wx.getStorageSync('defaultBuyList')[0]
                    });
                    wx.setStorageSync('buyList', wx.getStorageSync('defaultBuyList'));
                }
            });
        }
    },

    //页面显示时的操作
    onShow: function () {
        //记录本次打开页面时的缓存，用来判断是否有过更改
        this.setData({
            oldBuyMemoStorage: wx.getStorageSync('buyMemo'),
            oldBuyListStorage: wx.getStorageSync('buyList'),
            oldBuyChoosedStorage: wx.getStorageSync('buyChoosed')
        });

        //刷新已选count数
        let buyChoosed = wx.getStorageSync('buyChoosed');
        if (buyChoosed) {
            this.setData({
                count: buyChoosed.length,
            });
        } else {
            wx.cloud.database().collection("buyChoosed").doc(openid).get({
                success: res => {
                    wx.setStorageSync('buyChoosed', res.data.buyChoosed);
                    that.setData({
                        count: res.data.buyChoosed.length
                    });
                },
                fail: err => {
                    console.log("没有云端buyChoosed数据");
                }
            })
        }
    },

    //当有数据变化时保存数据到云服务器
    onHide: function () {
        const buyMemoDB = wx.cloud.database().collection("buyMemo");
        const buyListDB = wx.cloud.database().collection("buyList");
        const buyChoosedDB = wx.cloud.database().collection("buyChoosed");
        const buyMemo = wx.getStorageSync('buyMemo');
        const buyList = wx.getStorageSync('buyList');
        const buyChoosed = wx.getStorageSync('buyChoosed');
        //保存左侧菜单
        if (JSON.stringify(buyMemo) != JSON.stringify(this.data.oldBuyMemoStorage)) {
            buyMemoDB.where({
                _id: openid
            }).get().then(res => {
                if (res.data.length == 0) { //如果云端不存在该用户的buyMemo数据就添加
                    buyMemoDB.add({
                        data: {
                            _id: openid,
                            buyMemo: buyMemo
                        },
                        success: res => {
                            console.log("创建buyMemo数据表成功");
                        },
                        fail: err => {
                            console.log("创建buyMemo数据表出错" + err);
                        }
                    });
                } else { //如果云端存在该用户的buyMemo数据就更新
                    buyMemoDB.doc(openid).update({
                        data: {
                            buyMemo: buyMemo
                        },
                        success: res => {
                            console.log("更新buyMemo数据表成功");
                        },
                        fail: err => {
                            console.log("更新buyMemo数据表出错" + err);
                        }
                    })
                }
            })
        }
        //保存右侧列表
        if (JSON.stringify(buyList) != JSON.stringify(this.data.oldBuyListStorage)) {
            buyListDB.where({
                _id: openid
            }).get().then(res => {
                if (res.data.length == 0) {
                    buyListDB.add({
                        data: {
                            _id: openid,
                            buyList: buyList
                        },
                        success: res => {
                            console.log("创建buyList数据表成功");
                        },
                        fail: err => {
                            console.log("创建buyList数据表出错" + err);
                        }
                    });
                } else {
                    buyListDB.doc(openid).update({
                        data: {
                            buyList: buyList
                        },
                        success: res => {
                            console.log("更新buyList数据表成功");
                        },
                        fail: err => {
                            console.log("更新buyList数据表出错" + err);
                        }
                    })
                }
            })
        }
        //保存加入备忘录的材料
        if (JSON.stringify(buyChoosed) != JSON.stringify(this.data.oldBuyChoosedStorage)) {
            buyChoosedDB.where({
                _id: openid
            }).get().then(res => {
                //如果云端储存的列表为空就直接add添加
                if (res.data.length == 0) {
                    buyChoosedDB.add({
                        data: {
                            _id: openid,
                            buyChoosed: buyChoosed
                        },
                        success: res => {
                            console.log("创建buyChoosed数据表成功");
                        },
                        fail: err => {
                            console.log("创建buyChoosed数据表出错" + err);
                        }
                    });
                }
                //云端储存的列表不为空就更新
                else {
                    buyChoosedDB.doc(openid).update({
                        data: {
                            buyChoosed: buyChoosed
                        },
                        success: res => {
                            console.log("更新buyChoosed数据表成功");
                        },
                        fail: err => {
                            console.log("更新buyChoosed数据表出错" + err);
                        }
                    })
                }
            })
        }
    }
})